import { login, NavSearch, Search } from './tools.js'
import { APICartDel, APICartList, APICartUpdate } from './fetch.js';

$('.footer').load('../../layout/footer.html');
$('.header').load('../../layout/header.html', function () {
    login();
    NavSearch();
    Search();
})

//登录状态
if (sessionStorage.login_user) {
    async function CartList() {
        let { code, data } = await APICartList({
            username: sessionStorage.login_user
        })

        if (data.length < 1) {
            $('.cart-no-goodsItem').css('display', 'block')
        }


        let html = '';
        $.each(data, function (index, { img, gname, price, count, gid, cid }) {
            html += `
                      <tr class="cartList" data-cid="${cid}">
                      <td class="cart-cell cell-check">
                      <label class="cart-label">
      
                          <input type="checkbox" class="cart-select check-one" checked>

                      </label>
                  </td>
      
                  <td class="cart-cell cell-img">
                      <a class="link" href="./detail.html?gid=${gid}">
                          <img class="p-img" src="${img}" alt="${name}" />
                      </a>
                  </td>
      
                  <td class="cart-cell cell-info">
                      <a class="link" href="./detail.html?gid=${gid}">${gname}</a>
                  </td>
      
                  <td class="cart-cell cell-price">￥${price}</td>
      
                  <td class="cart-cell cell-count">
                      <span class="count-btn minus">-</span>
                      <input class="count-input" value="${count}"/>
                      <span class="count-btn plus">+</span>
                  </td>
      
                  <td class="cart-cell cell-total">￥${(count * price).toFixed(2)}</td>
                  <td class="cart-cell cell-opera">
                      <span class="link cart-delete">删除</span>
                  </td>
                  </tr>
              `
        })

        $('.main-content-item').html(html);
        getTotal();
    }
    CartList();


    // 修改数量
    $('.main-content-item').on('click', '.plus', function () {
        setCount(this, 1);
    })

    $('.main-content-item').on('click', '.minus', function () {
        setCount(this, -1);
    })


    // 删除单项
    $('.main-content-item').on('click', '.cart-delete', function () {
        var $items = $(this).parents('.cartList');
        APICartDel({
            cid: $items.attr('data-cid')
        }).then(({ code }) => {
            if (code) {
                alert('删除成功');
                $items.remove();
                checkAll();
                getTotal();
            } else {
                alert('删除失败');
            }
        })
    })

    //全选按钮
    $(document).on('change', '.check-all', function () {
        $('.check-one').prop('checked', $(this).prop('checked'));
        $('.check-all').prop('checked', $(this).prop('checked'));
        getTotal();
    })
 
    //单选按钮
    $('.main-content-item').on('click', '.check-one', function () {
        checkAll()
        getTotal();
    })

    checkAll();

} else {
    $('.no-login-cart').css('display', 'block')
}




//全选
function checkAll() {
    if ($('.check-one').length === $('.check-one:checked').length) {
        $('.check-all').prop('checked', true)
    } else {
        $('.check-all').prop('checked', false)
    }

}



//修改数量
let timeout;
function setCount(ele, tag) {
    var $items = $(ele).parents('.cartList');
    var price = $items.find('.cell-price').html().replace('￥', '');

    var count = $items.find('.cell-count .count-input').val() * 1;

    count += tag

    if (count <= 1) {
        count = 1
    }

    $items.find('.cell-count .count-input').val(count);

    $items.find('.cell-total').html(`￥${(count * price).toFixed(2)}`);

    getTotal();

    clearTimeout(timeout);
    timeout = setTimeout(function () {
        APICartUpdate({
            cid: $items.attr('data-cid'),
            count: $items.find('.count-input').val()
        }).then(data => {
            console.log(data);
        })
    }, 300)
}


//计算总价
function getTotal() {
    var money = 0;
    var count = 0;
    $('.check-one:checked').each(function (_, item) {
        count += $(item).parents('.cartList').find('.count-input').val() * 1;
        money += $(item).parents('.cartList').find('.cell-total').html().replace('￥', '') * 1;
    });

    $('.submit-total').html(`￥${money.toFixed(2)}`);
    $('.CountAll').html(`已选择${count}件`)
}